package com.holin.codenav.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
@RestController
public class FileUploadController {

    @PostMapping("/upload")
    public  String upload(String fileName, MultipartFile author, HttpServletRequest request) throws IOException{
        System.out.println(fileName);
        //获取图片的原始名称
        System.out.println(author.getOriginalFilename());
        // 文件类型
        System.out.println(author.getContentType());
        // 获取web服务器的运行目录，将文件存储到项目
        String path = request.getServletContext().getRealPath("/upload/");
        System.out.println(path);
        saveFile(author,path);
        return "上传成功";
    }

    public void saveFile(MultipartFile authorPhoto,String path) throws  IOException{
        // 判断存储的目录是否存在，如果不存在创建
        File dir = new File(path);
        if(!dir.exists()){
            // 创建目录
            dir.mkdir();
        }
        File file = new File(path+authorPhoto.getOriginalFilename());
        authorPhoto.transferTo(file);
    }
}
